package com.password.desktop.page;

import java.awt.Color;
import java.awt.Image;
import java.awt.event.ItemEvent;
import java.awt.event.MouseEvent;
import java.net.URL;
import java.util.List;
import java.util.Map;

import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;

import org.apache.commons.lang3.StringUtils;

import com.password.desktop.UI.AbstractMovedWindow;
import com.password.desktop.UI.ComboxRender;
import com.password.desktop.UI.ImageJLable;
import com.password.desktop.UI.PMButton;
import com.password.desktop.UI.PMTextArea;
import com.password.desktop.exception.NoLoginException;
import com.password.desktop.service.LoginService;
import com.password.desktop.service.SavedTextSecretService;
import com.password.desktop.util.MessageUtil;
import com.password.desktop.util.SysUtil;
import com.password.entity.User;

/**
 * 文本加密窗口
 * 
 * @author yzh
 * @date 2020年6月4日
 *
 */
public class TextEncrptWindow extends AbstractMovedWindow {

	private final static String selectItemFirstValue = "请选择";
	LoginService loginService = LoginService.builderLoginService();
	SavedTextSecretService textSecretSerice = SavedTextSecretService.build();

	private static final long serialVersionUID = 1L;

	private static final int HEIGHT_WINDOW = 480; // 窗口高度
	private static final int WIDTH_WINDOW = 720; // 窗口宽度
	private static final int HEIGHT_HEAD = 32;
	private static final int HEIGHT_TITLE = 48;
	private static final int HEIGHT_SELECTED = 48;
	private static final int HEIGHT_CONTENT = HEIGHT_WINDOW - HEIGHT_HEAD - HEIGHT_SELECTED - 2;
	private JPanel head; // 头部容器
	JLabel logo, minW, closeW;// logo,最小化，关闭

	JLabel encrpt, decrpt;// 加密和解密按钮
	JTextArea text, enText;// 加密和解密框

	public TextEncrptWindow() {
		getContentPane().add(getHead());
		getContentPane().add(getTitle("文本加密解密"));
		getContentPane().add(getSelect());
		getContentPane().add(getContent());
		initSet();
	}

	public void initSet() {
		this.setSize(WIDTH_WINDOW, HEIGHT_WINDOW);
		super.initSet();
		this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		this.setTitle("PM " + loginService.getCurrentUser().getUserName());
		setVisible(true);
	}

	public static void main(String[] args) {
		new TextEncrptWindow();
	}

	public JPanel getContent() {

		JPanel jContent = new JPanel();
		jContent.setOpaque(true);
		jContent.setBackground(Color.white);
		jContent.setLayout(null);
		jContent.setVisible(true);
		jContent.setBounds(0, HEIGHT_HEAD + HEIGHT_TITLE + HEIGHT_SELECTED + 2, WIDTH_WINDOW, HEIGHT_CONTENT);

		text = new PMTextArea();
		text.setBounds(10, 10, 298, HEIGHT_CONTENT - 60);
		enText = new PMTextArea();
		enText.setBounds(WIDTH_WINDOW - (298 + 10), 10, 298, HEIGHT_CONTENT - 60);

		encrpt = new PMButton("加密", PMButton.STYLE_SUCCESS, (s) -> {
			String text2 = text.getText();
			if (StringUtils.isNotBlank(text2)) {
				try {
					String encordText = textSecretSerice.encordText(text2);
					enText.setText(encordText);
				} catch (Exception e) {
					MessageUtil.showMessage(null, e.getMessage());
				}
			} else {
				MessageUtil.showMessage(null, "加密的文本不能为空");
			}
		});
		encrpt.setBounds(298 + 20, HEIGHT_CONTENT / 2 - 98, 80, 32);
		JLabel leftArrow = new ImageJLable(new ImageIcon(getResoure("images/leftArrow.png")));
		leftArrow.setBounds(298 + 15, HEIGHT_CONTENT / 2 - 148, 98, 64);

		decrpt = new PMButton("解密", PMButton.STYLE_INFO, (s) -> {
			String text2 = enText.getText();
			if (StringUtils.isNotBlank(text2)) {
				try {
					String encordText = textSecretSerice.decodeText(text2);
					text.setText(encordText);
				} catch (Exception e) {
					MessageUtil.showMessage(null, e.getMessage());
				}
			} else {
				MessageUtil.showMessage(null, "密文不能为空");
			}

		});
		decrpt.setBounds(298 + 20, HEIGHT_CONTENT / 2 + 32, 80, 32);
		JLabel rightArrow = new ImageJLable(new ImageIcon(getResoure("images/rightArrow.png")));
		rightArrow.setBounds(298 + 15, HEIGHT_CONTENT / 2 - 22, 98, 64);

		jContent.add(encrpt);
		jContent.add(leftArrow);
		jContent.add(decrpt);
		jContent.add(rightArrow);
		jContent.add(text);
		jContent.add(enText);

		return jContent;
	}

	/**
	 * 获取选择框组件
	 * 
	 * @author yzh
	 * @date 2020年6月5日
	 * 
	 * @return
	 */
	public JPanel getSelect() {
		JPanel jTitle = new JPanel();
		jTitle.setOpaque(true);
		jTitle.setBackground(Color.white);
		jTitle.setLayout(null);
		jTitle.setVisible(true);
		jTitle.setBounds(0, HEIGHT_HEAD + HEIGHT_TITLE + 1, WIDTH_WINDOW, HEIGHT_SELECTED);

		JLabel jlable = new JLabel("请选择已保存的密码:");
		jlable.setForeground(Color.black);
		jlable.setBounds(0, 0, 180, HEIGHT_SELECTED);
		jlable.setFont(SysUtil.FONT_DEFAULT_MIDDLE);
		jlable.setHorizontalAlignment(SwingConstants.CENTER);
		List<String> items = null;
		try {
			items = textSecretSerice.getItems();
		} catch (NoLoginException e) {
			MessageUtil.showMessage(null, "未登录");
			dispose();
			new LoginWindow();
			throw e;
		} catch (Exception e1) {
			MessageUtil.showMessage(null, e1.getMessage());
		}
		JComboBox<String> selectItem = new JComboBox<String>(new String[] { selectItemFirstValue }); // 选择组件
		if (items != null) {
			for (String it : items)
				selectItem.addItem(it);
		}
		selectItem.setBackground(Color.white);
		selectItem.setOpaque(true);
		selectItem.setBounds(180, 8, 210, 32);
		ComboxRender<String> render = new ComboxRender<String>();
		selectItem.setRenderer(render);
		selectItem.addItemListener((e) -> {
			if (e.getStateChange() == ItemEvent.SELECTED) {
				String selectedItem = (String) selectItem.getSelectedItem();
				if (!StringUtils.equals(selectedItem, selectItemFirstValue)) {
					try {
						Map<String, String> textForItem = textSecretSerice.getTextForItem(selectedItem);
						text.setText(textForItem.get("decrypt"));
						enText.setText(textForItem.get("encrypt"));
					} catch (Exception e1) {
						MessageUtil.showMessage(TextEncrptWindow.this, e1.getMessage());
					}
				}

			}
		});

		JLabel save = new PMButton("保存", "注意要加密完成之后再保存", PMButton.STYLE_SUCCESS, (s) -> {
			save(enText.getText(), selectItem.getSelectedItem().toString(), selectItem);
		});
		save.setBounds(420, 8, 80, 32);

		JLabel cancle = new PMButton("清空", PMButton.STYLE_INFO, (s) -> {
			text.setText(null);
			enText.setText(null);
			selectItem.setSelectedIndex(0);
		});
		cancle.setBounds(520, 8, 80, 32);

		JLabel delete = new PMButton("删除", PMButton.STYLE_DANGER, (s) -> {
			String t = (String) selectItem.getSelectedItem();
			if (!StringUtils.equals(t, selectItemFirstValue)) {
				MessageUtil.confirmMessage("是否删除所选择的[" + t + "]信息？", (e) -> {
					try {
						if (textSecretSerice.deleteItem(t)) {
							MessageUtil.showMessage(null, "删除成功！");
							selectItem.removeItem(t);
							enText.setText(null);
							text.setText(null);
						} else {
							MessageUtil.showMessage(null, "删除失败！");
						}
					} catch (Exception e1) {
						MessageUtil.showMessage(null, e1.getMessage());
					}
				}, null, null);
			}
		});
		delete.setBounds(620, 8, 80, 32);

		jTitle.add(delete);
		jTitle.add(cancle);
		jTitle.add(save);
		jTitle.add(selectItem);
		jTitle.add(jlable);
		return jTitle;
	}

	private void save(String enText, String title, JComboBox<String> selectItem) {
		if (StringUtils.isBlank(enText)) {
			MessageUtil.showMessage(null, "请先对文本进行加密再保存");
			return;
		}
		if (StringUtils.equals(title, selectItemFirstValue)) {
			title = null;
		}
		String confirmValue = (String) JOptionPane.showInputDialog(TextEncrptWindow.this, "设置密文的名称", "是否保存",
				JOptionPane.PLAIN_MESSAGE, null, null, title);
		if (StringUtils.isNotBlank(confirmValue)) {
			try {
				List<String> items2 = textSecretSerice.getItems();
				if (items2.contains(confirmValue)) {
					MessageUtil.confirmMessage("[" + confirmValue + "]已经存在，是否覆盖?", (v) -> {
						try {
							textSecretSerice.saveSecret(confirmValue, enText);
						} catch (Exception e) {
							MessageUtil.showMessage(null, e.getMessage());
						}
					}, null, null);
				} else {
					textSecretSerice.saveSecret(confirmValue, enText);
					selectItem.addItem(confirmValue);
				}
			} catch (Exception e1) {
				MessageUtil.showMessage(null, e1.getMessage());
			}

		}
	}

	/**
	 * 标题组件
	 * 
	 * @author yzh
	 * @date 2020年6月5日
	 * 
	 * @param title
	 * @return
	 */
	public JPanel getTitle(String title) {
		JPanel jTitle = new JPanel();
		jTitle.setOpaque(true);
		jTitle.setBackground(Color.white);
		jTitle.setLayout(null);
		jTitle.setVisible(true);
		jTitle.setBounds(0, HEIGHT_HEAD, WIDTH_WINDOW, HEIGHT_TITLE);

		JLabel txt = new JLabel(title);
		txt.setForeground(Color.black);
		txt.setBounds(0, 0, WIDTH_WINDOW, HEIGHT_TITLE);
		txt.setFont(SysUtil.FONT_DEFAULT_BLOD);
		txt.setHorizontalAlignment(SwingConstants.CENTER);

		jTitle.add(txt);

		return jTitle;
	}

	public JPanel getHead() {
		User currentUser = loginService.getCurrentUser();
		if (currentUser == null) {
			MessageUtil.showMessage(null, "未登录");
			dispose();
			new LoginWindow();
			throw new NoLoginException("未登录");
		}
		head = new JPanel();
		head.setBackground(new Color(153, 255, 204));
		head.setLayout(null);
		head.setVisible(true);
		head.setBounds(0, 0, WIDTH_WINDOW, HEIGHT_HEAD);
		head.setForeground(Color.WHITE);
		ImageIcon imageIcon = new ImageIcon(getResoure("素材/1.gif"));
		imageIcon.setImage(imageIcon.getImage().getScaledInstance(WIDTH_WINDOW, HEIGHT_HEAD, Image.SCALE_DEFAULT));
		JLabel backgroud = new JLabel();
		backgroud.setIcon(imageIcon);
		backgroud.setOpaque(false);
		JLabel title = new JLabel("PM " + currentUser.getUserName());
		logo = new JLabel(SysUtil.ICON_LOGO_MIDDLE);
		minW = new JLabel(SysUtil.ICON_MIN);
		closeW = new JLabel(SysUtil.ICON_CLOSE);
		backgroud.setBounds(0, 0, WIDTH_WINDOW, HEIGHT_HEAD);
		logo.setBounds(0, 0, HEIGHT_HEAD, HEIGHT_HEAD);
		title.setBounds(HEIGHT_HEAD + 2, 0, WIDTH_WINDOW - 64, HEIGHT_HEAD);
		title.setFont(SysUtil.FONT_DEFAULT_MIN);
		minW.setBounds(WIDTH_WINDOW - 64 - 4, 0, HEIGHT_HEAD, HEIGHT_HEAD);
		minW.setBackground(new Color(0, 0, 0, 0.3f));
		closeW.setBounds(WIDTH_WINDOW - 32, 0, HEIGHT_HEAD, HEIGHT_HEAD);
		closeW.setBackground(new Color(0, 0, 0, 0.3f));
		// 事件区域
		minW.addMouseListener(this);
		closeW.addMouseListener(this);

		head.add(logo);
		head.add(title);
		head.add(minW);
		head.add(closeW);
		head.add(backgroud);

		return head;
	}

	@Override
	public void mousePressed(MouseEvent e) {
		if (e.getSource() == minW) {
			setExtendedState(JFrame.ICONIFIED);
		} else if (e.getSource() == closeW) {
			dispose();
			new MenuWindow();
		} else if (e.getSource() == this) {
			super.mousePressed(e);
		}

	}

	@Override
	public void mouseEntered(MouseEvent e) {
		if (e.getSource() == minW) {
			minW.setOpaque(true);
			minW.setBackground(Color.lightGray);
		} else if (e.getSource() == closeW) {
			closeW.setOpaque(true);
			closeW.setBackground(Color.lightGray);
		}

	}

	@Override
	public void mouseExited(MouseEvent e) {
		if (e.getSource() == minW) {
			minW.setOpaque(false);
			minW.setBackground(new Color(0, 0, 0, 0.3f));
		} else if (e.getSource() == closeW) {
			closeW.setOpaque(false);
			closeW.setBackground(new Color(0, 0, 0, 0.3f));
		}
	}

	public URL getResoure(String path) {
		return this.getClass().getClassLoader().getResource(path);
	}
}
